package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.Recipe;
import com.recipedb.recipedb.entity.RecipeDraft;
import com.recipedb.recipedb.entity.Step;
import com.recipedb.recipedb.service.RecipeDraftService;
import com.recipedb.recipedb.service.RecipeService;
import com.recipedb.recipedb.service.StepService;
import com.recipedb.recipedb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

@RestController
@RequestMapping("/api/recipes")
public class RecipeMigrationController {

    @Autowired
    private RecipeDraftService draftService;

    @Autowired
    private RecipeService recipeService;

    @Autowired
    private StepService stepService;

    @Autowired
    private UserService userService;

    @PostMapping("/migrate")
    @Transactional
    public ResponseEntity<?> migrate(
            @RequestParam Long draftId,
            @RequestParam Long recipeId,
            Authentication authentication
    ) throws IOException {

        // 权限检查
        RecipeDraft draft = draftService.findById(draftId)
                .orElseThrow(() -> new RuntimeException("Draft not found"));
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!draft.getUserId().equals(currentUserId)) {
            throw new AccessDeniedException("无权操作该草稿");
        }

        Recipe recipe = recipeService.findById(recipeId)
                .orElseThrow(() -> new RuntimeException("Recipe not found"));

        String baseDir = "/var/www/recipe-app";

        // ========== 1. 封面迁移 ==========
        File draftCover = new File(baseDir + "/uploads/drafts/d" + String.format("%06d", draftId) + ".jpg");
        boolean coverMigrated = false;
        if (draftCover.exists()) {
            File recipeCover = new File(baseDir + "/uploads/recipes/cover/R" + String.format("%06d", recipeId) + ".jpg");
            Files.copy(draftCover.toPath(), recipeCover.toPath(), StandardCopyOption.REPLACE_EXISTING);
            recipe.setCoverImage("/uploads/recipes/cover/R" + String.format("%06d", recipeId) + ".jpg");
            recipeService.partialUpdate(recipeId, recipe);
            coverMigrated = true;
        }

        // ========== 2. 步骤图片迁移 ==========
        List<Step> steps = stepService.findByRecipeId(recipeId);
        List<Integer> missingSteps = new ArrayList<>();
        int migratedCount = 0;

        for (Step step : steps) {
            int stepOrder = step.getStepOrder(); // 从 1 开始
            File draftStep = new File(baseDir + "/uploads/drafts/d" + String.format("%06d", draftId) + "_0" + stepOrder + ".jpg");
            if (draftStep.exists()) {
                File recipeStep = new File(baseDir + "/uploads/recipes/steps/R" + String.format("%06d", recipeId) + "_S0" + stepOrder + ".jpg");
                Files.copy(draftStep.toPath(), recipeStep.toPath(), StandardCopyOption.REPLACE_EXISTING);
                step.setImagePath("/uploads/recipes/steps/R" + String.format("%06d", recipeId) + "_S0" + stepOrder + ".jpg");
                stepService.updateImagePath(step.getId(), step.getImagePath());
                migratedCount++;
            } else {
                step.setImagePath(null); // 或者设置默认占位图路径
                stepService.updateImagePath(step.getId(), step.getImagePath());
                missingSteps.add(stepOrder);
            }
        }

        // ========== 3. 返回结果 ==========
        Map<String, Object> result = new HashMap<>();
        result.put("coverMigrated", coverMigrated);
        result.put("stepsMigrated", migratedCount);
        result.put("missingSteps", missingSteps);

        return ResponseEntity.ok(result);
    }
}
